﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.HtmlFunc;

namespace Kooboo.CMS.SiteConverter.Parser
{
    public class ParserPoll
    {
        static Dictionary<ParserType, Type> ParserFactories;

        static ParserPoll()
        {
            ParserFactories = new Dictionary<ParserType, Type>();
            ParserFactories.Add(ParserType.Razor, typeof(Razor.ParserFactory));
            ParserFactories.Add(ParserType.WebForm, typeof(WebForm.ParserFactory));
            ParserFactories.Add(ParserType.NVelocity, typeof(NVelocity.ParserFactory));
        }

        public static void Register(ParserType type, Type factory)
        {
            var ancestor = typeof(IParserFactory);
            if (RuntimeKit.IsInherited(factory, ancestor))
            {
                ParserFactories[type] = factory;
            }
            else
            {
                throw new ArgumentException(string.Format("The type {0} you register is not a {1} type!", factory.Name, ancestor.Name));
            }
        }

        public static bool Unregister(ParserType type)
        {
            return ParserFactories.Remove(type);
        }

        public static IParserFactory GetParser(ParserType type, ParserContext context = null)
        {
            if (ParserFactories.ContainsKey(type))
            {
                if (context != null)
                    return (IParserFactory)RuntimeKit.CreateInstance(ParserFactories[type], context);
                return (IParserFactory)RuntimeKit.CreateInstance(ParserFactories[type]);
            }
            else
            {
                throw new ArgumentException(string.Format("Parser type:{0} is not support yet!", type.ToString()));
            }
        }
    }
}
